var treelistdate ; //数据的对象
var selection  ; //当前点击的对象
var treeDivId = '';//树位置的id，要带#号
var windowtype ='';//当前操作的窗体类型
var passflag = true;
var add_id = Math.floor(Math.random() * 60000 ) + 15;
var app_id = '';
var app_account = '';
var app_domain = '';

function combobox_4(id,json,editable,selectValue){		
	$("#"+id).combobox({   
	    data:json,   
	    valueField:'id',
	    textField:'text',
	    editable:editable,
	}).combobox("select",selectValue);	
}

function treeList(json){
	if(json == undefined){
		$(treeDivId).html('');
	}else{
			$(treeDivId).tree({  
		        data:json,  
		        method:"get",
		        animate:true,
		        lines:true,
		        onClick : function(node){
		        	//单击事件
		        	selection = $(treeDivId).tree('getSelected');
		        	clearmenu();
					clickmenu(node);
		        },
		        onDblClick : function(node){
		        	//双击事件
		        	removemenu('update');
		        },
		        onLoadSuccess:function(note){
		        	//加载完成事件
		        	$(treeDivId).tree('collapseAll');
		        }
		    });  
	}
}

//创建树
function buildtree(id){
	if(windowtype == 'add'){
			//修改树的请求
			$.ajax({
				type:"post",
				url:"weixinMenu/queryMenuTreeByS.do",
				data:{appId:app_id,appAccount:app_account,ihost:location.host,appDomain:app_domain},
				dataType:"json",
				success:function(data){
					if(data){
						treelistdate = data;
					}else{
						treelistdate = undefined ;
					}
					treeList(treelistdate);
				},
				error:function(){
					treelistdate = undefined ;
					$.messager.alert("网络异常","获取菜单失败",'error');
				}
		 	});
	}else if(windowtype == 'update'){
			//修改树的请求
			$.ajax({
				type:"post",
				url:"weixinMenu/queryMenuTree.do?id="+id,
				dataType:"json",
				success:function(data){
					if(data){
						treelistdate = data;
					}else{
						treelistdate = undefined ;
					}
					treeList(treelistdate);
				},
				error:function(){
					treelistdate = undefined ;
					$.messager.alert("网络异常","获取菜单失败",'error');
				}
		 	});
	}
	
	
}

function newparentmenu(){
	//父菜单限制
		if(treelistdate!=null && treelistdate!='' && treelistdate.length >= 3 ){
			$.messager.alert("操作失败","父菜单只能新建三个",'error');
			return ;
		}
	passflag = false;
	$(treeDivId).tree('select','');
	$(treeDivId).tree('collapseAll');
	clearmenu();
	if(windowtype == 'add'){
		$("#parentId").val(0);
	}else if(windowtype == 'update'){
		$("#parentIdUpdate").val(0);
	}
}

function newchildrenmenu(){
	selection = $(treeDivId).tree('getSelected');
	//子菜单限制及不在情况的限制
		if(selection == null || selection == '' ){
			$(treeDivId).tree('select','');
			$.messager.alert("操作失败","请选择父菜单进行操作",'error');
			return ;
		}
		if(selection.attributes.parentId!=0){
			$(treeDivId).tree('select','');
			$.messager.alert("操作失败","只能在父菜单下新建子菜单",'error');
			return ;
		}
		for(var i = 0 ; i<treelistdate.length ; i ++ ){
			if( treelistdate[i].id == selection.id ){
				if(treelistdate[i].children.length >= 5){
					$(treeDivId).tree('select','');
					$.messager.alert("操作失败","只能创建5个子菜单",'error');
					return ;
				}
			}
		}
	passflag = false;
	clearmenu();
	if(windowtype == 'add'){
		$("#parentId").val(selection.id);
	}else if(windowtype == 'update'){
		$("#parentIdUpdate").val(selection.id);
	}
}

/**
* 清除菜单位置
*/
function clearmenu(){
	if(windowtype == ''){
		$.messager.alert("操作失败","操作失败",'error');
		return ;
	}else if(windowtype == 'add'){
		$("#url").val("");
		$("#inputCode").val("");
		$("#muneName").val("");
		$('#add_form').find('input[name="mtype"]').val("");
		$("#menuId").val("");
		$("#parentId").val("");
		combobox_4("mtype",eval('[{id:"view",text:"链接"},{id:"click",text:"点击"}]'),false,"");
	}else if(windowtype == 'update'){
		$("#urlUpdate").val("");
		$("#inputCodeUpdate").val("");
		$("#muneNameUpdate").val("");
		$('#update_form').find('input[name="mtype"]').val("");
		$("#menuIdUpdate").val("");
		$("#parentIdUpdate").val("");
		combobox_4("mtypeUpdate",eval('[{id:"view",text:"链接"},{id:"click",text:"点击"}]'),false,"");
	}else{
		$.messager.alert("操作失败","操作失败",'error');
		return ;
	}
}

/**
* 点击填充菜单信息
*/
function clickmenu(node){
	with(node.attributes){
		if(windowtype == ''){
			$.messager.alert("操作失败","操作失败",'error');
			return ;
		}else if(windowtype == 'add'){
			combobox_4("mtype",eval('[{id:"view",text:"链接"},{id:"click",text:"点击"}]'),false,mtype);
			$("#url").val(url);
			$("#inputCode").val(inputCode);
			$("#muneName").val(name);
			$("#menuId").val(id);
			$("#parentId").val(parentId);
		}else if(windowtype == 'update'){
			combobox_4("mtypeUpdate",eval('[{id:"view",text:"链接"},{id:"click",text:"点击"}]'),false,mtype);
			$("#urlUpdate").val(url);
			$("#inputCodeUpdate").val(inputCode);
			$("#muneNameUpdate").val(name);
			$("#menuIdUpdate").val(id);
			$("#parentIdUpdate").val(parentId);
		}
	}
	passflag = false;
}

/**
* 删除菜单
*/
function removemenu(){
	selection = $(treeDivId).tree('getSelected');
	if(!selection || selection == null ){
		$.messager.alert("操作失败","请选择菜单项",'error');
		return ; 
	}
	$.messager.confirm('删除确认','确定删除该菜单？',function(f){
		if(f){
					var re_url = ''
					if(windowtype == 'add'){
						re_url = "weixinMenu/deleteMenuByS.do?strfalg="+selection.attributes.strfalg+"&id=";
					}else if(windowtype == 'update'){
						re_url = "weixinMenu/deleteMenu.do?id=";
					}
					$.ajax({
						type:"post",
						url:re_url + selection.id,
						dataType:"json",
						success:function(res){
							if( res > 0 ){
								dataremovemenu(selection.id,selection.attributes.parentId);
								clearmenu();
								$(treeDivId).tree('remove',selection.target);
								selection = $(treeDivId).tree('getSelected');
							}else{
								$.messager.alert("操作失败","删除菜单失败",'error');
							}
						},
						error:function(){
							$.messager.alert("网络异常","删除菜单失败",'error');
						}
				 	});
		}
	})
		
	
}

/**
*保存当下操作的菜单
*/
function savemenu(){
	if(passflag){
		return ;
	}
	passflag = true;
	selection = $(treeDivId).tree('getSelected');
	var gid  ;
	var mtype;
	var name ;
	var inputCode;
	var url  ;
	var id   ;
	var parentId;
	var posturl = '';
	if(windowtype == ''){
		$.messager.alert("操作失败","操作失败",'error');
		return ;
	}else if(windowtype == 'add'){
		url = $("#url").val()||"";
		inputCode = $("#inputCode").val()||"";
		name = $("#muneName").val()||"";
		mtype = $('#add_form').find('input[name="mtype"]').val()||"";
		gid = $("#gid").val()||0;
		id = $("#menuId").val() || add_id;
		parentId = $("#parentId").val()||0;
		if($("#menuId").val() == ''){
			posturl = 'weixinMenu/addMenuByS.do';
		}else{
			posturl = 'weixinMenu/updateMenuByS.do';
		}
	}else if(windowtype == 'update'){
		url = $("#urlUpdate").val()||"";
		inputCode = $("#inputCodeUpdate").val()||"";
		name = $("#muneNameUpdate").val()||"";
		mtype = $('#update_form').find('input[name="mtype"]').val()||"";
		gid = $("#gidUpdate").val()||0;
		id = $("#menuIdUpdate").val();
		parentId = $("#parentIdUpdate").val()||0;
		if(id== ''){
			posturl = 'weixinMenu/addMenuByU.do';
		}else{
			posturl = 'weixinMenu/updateMenuByU.do';
		}
		
	}else{
		$.messager.alert("操作失败","操作失败",'error'); 
		return ;
	}
	try {
		if(parentId != 0){
			if( mtype == '' ) throw '请选择菜单类型';
			if( mtype == 'click' && inputCode == '' ) throw '请输入关键词';
			if( mtype == 'view' && url == '' ) throw '请输入链接';
		}else{
			
		}
		if( name == '' || name.replace(/[^\x00-\xff]/g, "**").length > 16) throw '菜单名字不可超过16字节';
		if( gid == 0 && ( name == '' || name.replace(/[^\x00-\xff]/g, "**").length > 8) ) throw '菜单名字不可超过8字节';
	} catch (e) {
		passflag = false;
		$.messager.alert("操作失败",e,'error');
		return ;
	}
	var newmenu = new menu(gid,mtype,name,inputCode,url,id,parentId,selection );
	$.ajax({
		type:"post",
		url:posturl,
		data:newmenu,
		dataType:"json",
		success:function(res){
			if( res > 0 ){
				if(newmenu.id == '' || ( windowtype == 'add' && $("#menuId").val() == '' ) ){
					newmenu.id = id || res;
					addtreenode(newmenu);
				}else{
					updatetreenode(newmenu);
				}
				add_id = res;
				selection = $(treeDivId).tree('getSelected','');
			}else{
				passflag = false;
				$.messager.alert("操作失败","操作失败",'error');
			}
		},
		error:function(){
			passflag = false;
			$.messager.alert("网络异常","保存失败",'error');
		}
 	});
}

/**
*增加一个树的节点
*/
function addtreenode(menu){
		var amenu = {};
		amenu.id = menu.id;
		amenu.text = menu.name;
		amenu.attributes = menu;
		amenu.children = [];
	if(menu.parentId == 0 ){
		if(treelistdate==undefined || treelistdate == null){
			treelistdate = [];
		}
		treelistdate.push(amenu)
	}else{
		for(var i = 0 ; i<treelistdate.length ; i ++ ){
			if( treelistdate[i].id == menu.parentId ){
				if(treelistdate[i].children && treelistdate[i].children.length > 0){
					
				}else{
					treelistdate[i].children = [] ;
				}
				treelistdate[i].children.push(amenu);
			}
		}
	}
	treeList(treelistdate);
	$(treeDivId).tree('select',$('div[node-id='+menu.id+']'));
	if(menu.parentId != 0){
		$(treeDivId).tree('expand',$('div[node-id="'+menu.parentId+'"]'));
	}
	selection = $(treeDivId).tree('getSelected');
	$(selection.target).trigger('click');
}

function updatetreenode(menu){
	var amenu = {};
	amenu.id = menu.id;
	amenu.text = menu.name;
	amenu.attributes = menu;
	amenu.children = [];
	if(menu.parentId == 0 ){
		for(var i = 0 ; i < treelistdate.length ; i++ ){
			if( (menu.strfalg != '' && menu.strfalg == treelistdate[i].attributes.strfalg) || menu.id == treelistdate[i].id ){
				treelistdate[i] = amenu;
			}
		}
	}else{
		for(var i = 0 ; i<treelistdate.length ; i ++ ){
			if( treelistdate[i].id == menu.parentId ){
				for(var j = 0 ; j < treelistdate[i].children.length ; j++ ){
					if( ( menu.strfalg && menu.strfalg != '' && menu.strfalg == treelistdate[i].children[j].attributes.strfalg) || menu.id == treelistdate[i].children[j].id ){
						treelistdate[i].children[j] = amenu;
					}
				}
			}
		}
	}
	treeList(treelistdate);
	$(treeDivId).tree('select',$('div[node-id='+menu.id+']'));
	if(menu.parentId != 0){
		$(treeDivId).tree('expand',$('div[node-id="'+menu.parentId+'"]'));
	}
}

/**
* 删除内容里面的菜单
*/
function dataremovemenu(id , pid){
	var remove_numi = 99;
	var remove_numj = 99;
	if(pid == 0){
		for(var i = 0 ; i<treelistdate.length ; i ++ ){
			if( treelistdate[i].id == id ){
				remove_num = i ;
			}
		}
		treelistdate.splice(remove_num,1);
	}else{
		var doflag = false;
		for(var i = 0 ; i<treelistdate.length ; i ++ ){
			if( treelistdate[i].id == pid ){
				for(var j = 0 ; j<treelistdate[i].children.length ; j ++ ){
					if( treelistdate[i].children[j].id == id ){
						doflag = true;
						remove_numi = i ;
						remove_numj = j ;
					}
				}
				if(doflag){
					treelistdate[remove_numi].children.splice(remove_numj,1);
					doflag = false;
				}
			}
		}
	}
}

/**
*构造一个菜单对象
*/
function menu(a,b,c,d,e,f,g,h){
	this.gid = a  ;
	this.mtype =b ;
	this.name = c ;
	this.inputCode = d;
	this.url = e  ;
	this.id = f   ;
	this.parentId = g;
	if(h && h.attributes && h.attributes.strfalg !=''){
		this.strfalg = h.attributes.strfalg;
	}else{
		this.strfalg = randomString(16);
	}
}

/**
 * 随即字符串
 */
function randomString(len){
	len = len || 16 ;
	var $char = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	var maxpos = $char.length;
	var rstr = '';
	for(var i = 0 ; i < len ; i ++){
		rstr += $char.charAt(Math.floor(Math.random()*maxpos));
	}
	return rstr;
}

/**
 * 更正为授权链接
 * @param textarea
 */
function toOAuth(textarea){
	var s = $('#'+textarea).val();
	if(s!='' && s.indexOf('redirect_uri=http') == -1 ){
		if(app_id==''){
			$.messager.alert("操作失败","请先行设置微信公众号信息",'error');
			return ;
		}
		if( s.indexOf('http') == -1 || s.indexOf('https') == -1 ){
			s = 'http://' + s;
		}
		s = 'http://'+location.host+'/phoneWeb/weixin_index.html?appc='+app_account+'&orgsc='+app_domain+'&turl='+ s;
		s = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='+app_id+'&redirect_uri='+encodeURIComponent(s)+'&response_type=code&scope=snsapi_userinfo&state=1&connect_redirect=1#wechat_redirect';
		$('#'+textarea).val(s);
	}
}

/**
 * 获取账户跟APPID
 */
function getAccountAndAppid(){
	$.ajax({
		   type: "POST",
		   url: getTimeURL("weixinAccount/queryBySchoolId.do"),
		   async: false,
		   success: function(data){
			   if( data != null ){
				   app_id = data.appid;
				   app_account = data.account;
			   }else{
				   
			   }
		   }
		});
}

function buildmenu(id){
	if(app_account==''){
		$.messager.alert("操作失败","请先行设置微信公众号信息",'error');
		return ;
	}
	$.messager.confirm('发布确认','确定发布菜单？',function(f){
		if(f){
				$.ajax({
					   type: "POST",
					   url: getTimeURL("../wxapi/publishMenu/"+app_account+".do?gid="+id),
					   async: false,
					   success: function(data){
						   if( data == 'ok' ){
							   $.messager.alert("操作成功","发布成功");
						   }else{
							   $.messager.alert("操作失败","发布失败",'error');
						   }
					   },
						error:function(){
							$.messager.alert("网络异常","发布失败",'error');
						}
				});
		}
	})
}
